#include "StdAfx.h"
#include "DeskTopS.h"

#define  ChannelID 55001

HWND DeskTopS::m_hWnd = NULL;

void CALLBACK DeskTopS::threadWork_1(SOCKET s)
{
	    if(Auth(s,ChannelID) < 0)
		   return;

		Jpeg2RgbScreen * m_Jpeg2RgbScreen = new Jpeg2RgbScreen;
		if (!m_Jpeg2RgbScreen) return;

		m_Jpeg2RgbScreen->Init(NULL);
		::SendMessage(m_hWnd,WM_MSG_ACCEPT,(WPARAM)m_Jpeg2RgbScreen,(LPARAM)s);
		while(TRUE)
		{
			MessageHeader header2;
			memset(&header2,0,sizeof(MessageHeader));
			int ret = recv(s,(char*)&header2,sizeof(MessageHeader),0);
			if (ret == SOCKET_ERROR)
			{
				break;
			}	
			if (header2.version != 0x19780927)
			{
				closesocket(s);
				break;
			}

			ScreenHeader msg;
			ret =-1;
		    ret = recv(s,(char*)&msg,sizeof(ScreenHeader),0);
			if (ret == SOCKET_ERROR)
			{
				break;
			}	

			char * lpData  = (char *)GlobalAlloc(GMEM_FIXED,msg.dwFileSize );
			memset(lpData,0,msg.dwFileSize );
			int rev = 0;
			ret =-1;

			while(rev < msg.dwFileSize)
			{
				ret = recv(s,(char*)&lpData[rev],msg.dwFileSize-rev,0);
				if (ret < 0 )
				{
					break;	
				}

				rev += ret;
			}
			if (rev == msg.dwFileSize)
			{
				m_Jpeg2RgbScreen->SetScreenData(msg,(BYTE *)lpData);
			}

			if (lpData)
			{
				GlobalFree(lpData);
			}
	

		}
		/**free memory*/
		if(m_Jpeg2RgbScreen) 
		{
			delete m_Jpeg2RgbScreen;
			m_Jpeg2RgbScreen = NULL;
		}
}
int DeskTopS::start(char* ip,int port)
{
	return client.StartClient(ip,port,threadWork_1);
}
int DeskTopS::Auth(SOCKET client,unsigned int channelID)
{
	MessageHeader header;
	memset(&header,0,sizeof(header));
	header.packageType = AUTH;
	header.channelID = ChannelID;
	header.length = 12;
	header.version = 0x19780927;
	struct Msg{
		MessageHeader head;
		int ownerID;
		int groupID;
		int channelID;
	};
	Msg g_msg;
	g_msg.head = header;
	g_msg.groupID = 1;
	g_msg.ownerID = 12345;
	g_msg.channelID = ChannelID;
	int ret = send(client, (char*)&g_msg, sizeof(Msg), 0);
	if (ret == SOCKET_ERROR)
	{
		return -1;
	}
	memset(&header,0,sizeof(header));
	ret = -1;
	ret = recv(client, (char*)&header, sizeof(MessageHeader), 0);
	if (ret == SOCKET_ERROR)
	{
		return -1;
	}
	if (header.packageType == AUTH_SUCCESS)
	{
		return 1;
	}

	return 0;
}
void  DeskTopS::setHwnd(HWND hwnd)
{
	m_hWnd = hwnd;
}